<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
      <el-form-item :label="t('pickBatch.fields.batchName')" prop="batchName">
        <el-input
          v-model="queryParams.batchName"
          :placeholder="t('common.inputTextPlaceholder') + t('pickBatch.fields.batchName')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />{{ t('common.search') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />{{ t('common.reset') }}
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['recruit:pick-batch:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" />
          {{ t('action.add') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <vxe-toolbar ref="toolbarRef" custom />
    <vxe-table
      id="iPickBatch-table"
      ref="tableRef"
      v-loading="loading"
      :data="list"
      stripe
      :custom-config="vxeTableConfig"
      :column-config="{ resizable: true }"
      :size="vxeTableSize"
    >
      <vxe-column :title="t('common.index')" type="seq" field="seq" width="60" align="center" />
      <vxe-column
        :title="t('pickBatch.fields.batchName')"
        field="batchName"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('pickBatch.fields.year')"
        field="year"
        align="center"
        show-header-overflow
        show-overflow
        min-width="50"
      />
      <vxe-column
        :title="t('pickBatch.fields.applyStartTime')"
        field="applyStartTime"
        align="center"
        show-header-overflow
        show-overflow
        min-width="120"
        :formatter="vxeDateFormatter"
      />
      <vxe-column
        :title="t('pickBatch.fields.applyEndTime')"
        field="applyEndTime"
        align="center"
        show-header-overflow
        show-overflow
        min-width="120"
        :formatter="vxeDateFormatter"
      />
      <vxe-column
        :title="t('pickBatch.fields.reviewStartTime')"
        field="reviewStartTime"
        align="center"
        show-header-overflow
        show-overflow
        min-width="120"
        :formatter="vxeDateFormatter"
      />
      <vxe-column
        :title="t('pickBatch.fields.reviewEndTime')"
        field="reviewEndTime"
        align="center"
        show-header-overflow
        show-overflow
        min-width="120"
        :formatter="vxeDateFormatter"
      />
      <vxe-column
        :title="t('pickBatch.fields.applyCount')"
        field="applyCount"
        align="center"
        show-header-overflow
        show-overflow
        min-width="60"
      />
      <vxe-column
        :title="t('pickBatch.fields.reviewCount')"
        field="reviewCount"
        align="center"
        show-header-overflow
        show-overflow
        min-width="60"
      />
      <vxe-column
        :title="t('pickBatch.fields.votedCount')"
        field="votedCount"
        align="center"
        show-header-overflow
        show-overflow
        min-width="60"
      />
      <vxe-column
        :title="t('pickBatch.fields.unVotedCount')"
        field="unVotedCount"
        align="center"
        show-header-overflow
        show-overflow
        min-width="60"
      />
      <vxe-column
        :title="t('common.operate')"
        field="operator"
        align="center"
        fixed="right"
        width="200"
      >
        <template #default="scope">
          <el-button link type="primary" @click="copyApplyLink(scope.row.id)">
            {{ t('pickBatch.index.operate.copyApplyLink') }}
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleSetApplyTemplate(scope.row)"
            v-hasPermi="['recruit:pick-batch:update']"
          >
            {{ t('pickBatch.index.operate.setApplyTemplate') }}
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleSetReviewer(scope.row)"
            v-hasPermi="['recruit:pick-batch:update']"
          >
            {{ t('pickBatch.index.operate.setReviewer') }}
          </el-button>
          <el-button link type="primary" @click="gotoDetail(scope.row.id)">
            {{ t('pickBatch.index.operate.applyDetail') }}
          </el-button>
          <el-button link type="primary" @click="handleExportPassed(scope.row)">
            {{ t('pickBatch.index.operate.exportPassed') }}
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['recruit:pick-batch:update']"
          >
            {{ t('action.edit') }}
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['recruit:pick-batch:delete']"
          >
            {{ t('action.delete') }}
          </el-button>
        </template>
      </vxe-column>
    </vxe-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <PickBatchForm ref="formRef" @success="getList" />
  <!-- 设置申请表模板 -->
  <SetTemplateForm ref="setTemplateFormRef" @success="getList" />
  <!-- 设置导师遴选评委 -->
  <SetPickBatchMentor ref="setPickBatchMentorRef" @update="getList" />
</template>

<script setup lang="ts">
import { vxeDateFormatter } from '@/utils/formatTime'
import { PickBatchApi, PickBatchVO } from '@/api/recruit/pickbatch'
import PickBatchForm from './PickBatchForm.vue'
import SetTemplateForm from './SetTemplateForm.vue'
import SetPickBatchMentor from './SetPickBatchMentor.vue'
import type { VxeTablePropTypes, VxeToolbarInstance, VxeTableInstance } from 'vxe-table'
import { useAppStore } from '@/store/modules/app'
import { useClipboard } from '@vueuse/core'
import { PickDetailApi } from '@/api/recruit/pickdetail'
import download from '@/utils/download'
import { ElLoading } from 'element-plus'

/** 导师遴选批次 列表 */
defineOptions({ name: 'PickBatch' })

const router = useRouter()
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const { copy } = useClipboard() // 复制

const toolbarRef = ref<VxeToolbarInstance>()
const tableRef = ref<VxeTableInstance>()

const loading = ref(true) // 列表的加载中
const list = ref<PickBatchVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  advanced: undefined,
  batchName: undefined,
  year: undefined,
  applyStartTime: undefined,
  applyEndTime: undefined,
  reviewStartTime: undefined,
  reviewEndTime: undefined
})
const queryFormRef = ref() // 搜索的表单

const vxeTableConfig: VxeTablePropTypes.CustomConfig = {
  storage: true,
  mode: 'drawer',
  checkMethod({ column }) {
    return !['seq', 'operator'].includes(column.field)
  }
}

const appStore = useAppStore()
const vxeTableSize = computed(() => appStore.getCurrentSizeVxe)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await PickBatchApi.getPickBatchPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  ;(queryParams as any).advanced = undefined
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref<InstanceType<typeof PickBatchForm>>()
const openForm = (type: string, id?: number) => {
  formRef.value?.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await PickBatchApi.deletePickBatch(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 复制报名链接 */
const copyApplyLink = (id: number) => {
  const link = `${window.location.origin}/mentor-apply/${id}`
  copy(link)
    .then(() => {
      message.success(t('common.copySuccess'))
    })
    .catch(() => {
      message.error(t('common.copyFailed'))
    })
}

// 导出已通过
const handleExportPassed = async (item: PickBatchVO) => {
  let loading: any = undefined
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    loading = ElLoading.service({
      lock: true,
      text: t('common.exporting'),
      background: 'rgba(0, 0, 0, 0.7)'
    } as any)
    const data = await PickDetailApi.exportPickDetail(item.id, true)
    download.excel(data, `${item.batchName}-导师遴选-已通过名单.xlsx`)
  } finally {
    loading?.close()
  }
}

// 进入批次申请详情页
const gotoDetail = (id: number) => {
  router.push({
    path: `/recruit/pick-batch/${id}`
  })
}

// ======= 设置申请表模板 =======
const setTemplateFormRef = ref<InstanceType<typeof SetTemplateForm>>()

// 设置申请表模板
const handleSetApplyTemplate = (item: PickBatchVO) => {
  setTemplateFormRef.value?.open(item)
}

// ======= 设置评委 =======
const setPickBatchMentorRef = ref<InstanceType<typeof SetPickBatchMentor>>()

// 设置评委
const handleSetReviewer = (item: PickBatchVO) => {
  setPickBatchMentorRef.value?.open(item.id)
}

/** 初始化 **/
onMounted(() => {
  getList()

  const table = tableRef.value
  const toolbar = toolbarRef.value
  if (table && toolbar) {
    table.connect(toolbar)
  }
})
</script>
